package com.group01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.group01.dto.Commodity.CommodityInsertInfoDTO;
import com.group01.dto.Commodity.CommodityUpdateInfoDTO;
import com.group01.enums.CodeAndMessageEnum;
import com.group01.mapper.CategoryMapper;
import com.group01.pojo.Category;
import com.group01.pojo.Commodity;
import com.group01.result.PageTemplate;
import com.group01.result.Result;
import com.group01.service.CommodityService;
import com.group01.mapper.CommodityMapper;
import com.group01.utils.BeanCopyUtils;
import com.group01.vo.Commodity.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;

/**
* @author 19559
* @description 针对表【es_commodity(商品表)】的数据库操作Service实现
* @createDate 2024-06-21 15:21:49
*/
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements CommodityService{

    /**
     * 注入mapper
     */
    private final CommodityMapper commodityMapper;
    private final CategoryMapper categoryMapper;

    public CommodityServiceImpl(CommodityMapper commodityMapper, CategoryMapper categoryMapper) {
        this.commodityMapper = commodityMapper;
        this.categoryMapper = categoryMapper;
    }

    /**
     * 分页+条件查询图书信息
     * @param pageNum 页码
     * @param pageSize 页面大小
     * @param categoryId 分类id
     * @param query 关键字
     * @return {@link Result }<{@link PageTemplate }<{@link CommodityGetPageVO }>>
     */
    @Override
    public Result<PageTemplate<CommodityGetPageVO>> getPage(Integer pageNum, Integer pageSize, Integer categoryId, String query) {
        MPJLambdaWrapper<Commodity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(Commodity.class)
                .selectAs(Category::getName , Commodity::getCategoryName)
                .leftJoin(Category.class, Category::getId, Commodity::getCategoryId)
                .eq(categoryId != null,Commodity::getCategoryId, categoryId)
                .or()
                .like(StringUtils.hasText(query),Commodity::getName, query)
                .or()
                .like(StringUtils.hasText(query),Commodity::getAuthor, query)
                .or()
                .like(StringUtils.hasText(query),Commodity::getPublisher, query);
        Page<Commodity> page = new Page<>(pageNum,pageSize);
        commodityMapper.selectPage(page,queryWrapper);
        List<CommodityGetPageVO> vos = BeanCopyUtils.copyBeanList(page.getRecords(), CommodityGetPageVO.class);
        if(vos == null) {
            return Result.error(CodeAndMessageEnum.FIND_ITEMS_NONE, null);
        }
        //
        return Result.success(CodeAndMessageEnum.FIND_RESULT, new PageTemplate<>(page.getTotal(), vos));
    }

    /**
     * 根据分类ID获取图书信息
     * @param categoryId 分类Id
     * @return {@link Result }<{@link List }<{@link CommodityGetInfoByCateIdVO }>>
     */
    @Override
    public Result<List<CommodityGetInfoByCateIdVO>> getBooksByCategoryId(Integer categoryId) {

        Category category = categoryMapper.selectById(categoryId);
        if(category == null) {
            return Result.error(CodeAndMessageEnum.FIND_CATEGORY_ID_FAIL, null);
        }

        LambdaQueryWrapper<Commodity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Commodity::getCategoryId, categoryId);

        List<Commodity> commodities = commodityMapper.selectList(queryWrapper);

        // Bean拷贝
        List<CommodityGetInfoByCateIdVO> vos = BeanCopyUtils.copyBeanList(commodities, CommodityGetInfoByCateIdVO.class);

        return Result.success(CodeAndMessageEnum.FIND_RESULT, vos);
    }

    /**
     * 根据id获取图书信息
     * @param id 图书id
     * @return {@link Result }<{@link CommodityGetInfoByIdVO }>
     */
    @Override
    public Result<CommodityGetInfoByIdVO> getCommodityById(Integer id) {
        Commodity commodity = commodityMapper.selectById(id);
        if(commodity == null) {
            return Result.error(CodeAndMessageEnum.FIND_RESULT_FAIL, null);
        }
        MPJLambdaWrapper<Commodity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(Commodity.class)
                .selectAs(Category::getName , Commodity::getCategoryName)
                .leftJoin(Category.class, Category::getId, Commodity::getCategoryId)
                .eq(Commodity::getId, id);
        commodity = commodityMapper.selectOne(queryWrapper);
        CommodityGetInfoByIdVO vo = BeanCopyUtils.copyBean(commodity, CommodityGetInfoByIdVO.class);
        return Result.success(CodeAndMessageEnum.FIND_RESULT, vo);
    }

    /**
     * 新增图书
     * @param commodityInsertInfoDTO 新增图书传输数据DTO
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> addCommodity(CommodityInsertInfoDTO commodityInsertInfoDTO) {
        Category category = categoryMapper.selectById(commodityInsertInfoDTO.getCategoryId());
        if (category == null) {
            return Result.error(CodeAndMessageEnum.FIND_CATEGORY_ID_FAIL);
        }

        // Bean拷贝
        commodityMapper.insert(BeanCopyUtils.copyBean(commodityInsertInfoDTO, Commodity.class));
        return Result.success(CodeAndMessageEnum.INSERT_SUCCESS);
    }

    /**
     * 修改图书状态
     * @param id 图书id
     * @param status 状态值
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> updateCommodityStatus(Integer id, Integer status) {
        Commodity commodity = commodityMapper.selectById(id);
        if(commodity == null) {
            return Result.error(CodeAndMessageEnum.FIND_RESULT_FAIL);
        }

        LambdaUpdateWrapper<Commodity> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Commodity::getId, id)
                .set(Commodity::getStatus, status);

        commodityMapper.update(queryWrapper);
        return Result.success(CodeAndMessageEnum.UPDATE_SUCCESS);
    }

    /**
     * 修改图书
     * @param commodityUpdateInfoDTO 修改图书传输数据DTO
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> updateCommodity(CommodityUpdateInfoDTO commodityUpdateInfoDTO) {
        Category category = categoryMapper.selectById(commodityUpdateInfoDTO.getCategoryId());

        if (category == null) {
            return Result.error(CodeAndMessageEnum.FIND_CATEGORY_ID_FAIL, null);
        }

        Commodity commodity = commodityMapper.selectById(commodityUpdateInfoDTO.getId());

        if(commodity == null) {
            return Result.error(CodeAndMessageEnum.FIND_RESULT_FAIL, null);
        }

        commodity = BeanCopyUtils.copyBean(commodityUpdateInfoDTO, Commodity.class);

        // Bean拷贝
        commodityMapper.updateById(commodity);

        return Result.success(CodeAndMessageEnum.UPDATE_SUCCESS);

    }

    /**
     * 根据图书ID删除图书信息
     * @param id 图书id
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> deleteCommodityById(Integer id) {
        Commodity commodity = commodityMapper.selectById(id);
        if(commodity == null) {
            return Result.error(CodeAndMessageEnum.FIND_COMMODITY_ID_FAIL, null);
        }
        commodityMapper.deleteById(id);
        return Result.success(CodeAndMessageEnum.DELETE_SUCCESS);
    }

    /**
     * 批量删除图书（商品）信息
     * @param ids 图书（商品）id集合
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> deleteCommodityByIds(List<Integer> ids) {
        commodityMapper.deleteBatchIds(ids);
        return Result.success(CodeAndMessageEnum.DELETE_MANY_SUCCESS);
    }

    /**
     * 首页展示图书信息（只展示20本）
     * @return {@link Result }<{@link List }<{@link CommodityShowVO }>>
     */
    @Override
    public Result<List<CommodityShowVO>> showBooks() {
        Page<Commodity> page = new Page<>(1, 20);
        commodityMapper.selectPage(page, null);
        return Result.success(CodeAndMessageEnum.FIND_RESULT, BeanCopyUtils.copyBeanList(page.getRecords(), CommodityShowVO.class));
    }

    /**
     * 根据书名、作者、出版社检索图书信息
     * @param query 检索条件
     * @return {@link Result }<{@link List }<{@link CommodityShowVO }>>
     */
    @Override
    public Result<List<CommodityShowVO>> searchBook(String query) {
        LambdaQueryWrapper<Commodity> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.hasText(query)) {
            queryWrapper
                    .like(Commodity::getName , query)
                    .or(wrapper ->
                            wrapper.like(Commodity::getAuthor , query)
                    )
                    .or(wrapper ->
                            wrapper.like(Commodity::getPublisher , query)
                    );
        }
        List<Commodity> commodities = commodityMapper.selectList(queryWrapper);

        return Result.success(CodeAndMessageEnum.FIND_RESULT, BeanCopyUtils.copyBeanList(commodities, CommodityShowVO.class));
    }

    /**
     * 根据分类检索图书信息
     * @param id 分类id
     * @return {@link Result }<{@link List }<{@link CommodityShowVO }>>
     */
    @Override
    public Result<List<CommodityInfoVO>> findByCategory(Integer id) {
        if(categoryMapper.selectById(id) == null) {
            return Result.error(CodeAndMessageEnum.FIND_CATEGORY_ID_FAIL, null);
        }
        LambdaQueryWrapper<Commodity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Commodity::getCategoryId , id);

        List<Commodity> commodities = commodityMapper.selectList(queryWrapper);

        return Result.success(CodeAndMessageEnum.FIND_RESULT, BeanCopyUtils.copyBeanList(commodities, CommodityInfoVO.class));
    }

    /**
     * 管理端修改图书信息数据回显
     * @param id 图书id
     * @return {@link Result }<{@link CommodityGetPageVO }>
     */
    @Override
    public Result<CommodityGetPageVO> getCommodityByIdForBackend(Integer id) {
        MPJLambdaWrapper<Commodity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(Commodity.class)
                .selectAs(Category::getName, Commodity::getCategoryName)
                .leftJoin(Category.class, Category::getId, Commodity::getCategoryId)
                .eq(Commodity::getId, id);

        Commodity commodity = commodityMapper.selectOne(queryWrapper);
        return Result.success(CodeAndMessageEnum.FIND_RESULT, BeanCopyUtils.copyBean(commodity, CommodityGetPageVO.class));
    }

    /**
     * 获取所有图书信息
     * @param pageNum 页码
     * @param pageSize 页面大小
     * @return {@link Result }<{@link List }<{@link CommodityShowVO }>>
     */
    @Override
    public Result<List<CommodityShowVO>> getAllBooks(Integer pageNum, Integer pageSize) {
        Page<Commodity> page = new Page<>(pageNum, pageSize);
        commodityMapper.selectPage(page, null);
        return Result.success(CodeAndMessageEnum.FIND_RESULT, BeanCopyUtils.copyBeanList(page.getRecords(), CommodityShowVO.class));
    }

}




